package com.paishen.peiniwan.module.profile;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.util.DateUtils;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.DateUtil;
import com.paishen.common.util.LogUtil;
import com.paishen.common.widget.TitleLayout;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.Once;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.PhotoDao;
import com.paishen.peiniwan.database.UserDao;
import com.paishen.peiniwan.database.util.ModelConverter;
import com.paishen.peiniwan.frame.ColorEvaluator;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.CollectedInfo;
import com.paishen.peiniwan.frame.http.entity.CommentInfo;
import com.paishen.peiniwan.frame.http.entity.Photo;
import com.paishen.peiniwan.frame.http.entity.User;
import com.paishen.peiniwan.frame.http.entity.UserTag;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.peiniwan.frame.widget.PictureLayout;
import com.paishen.peiniwan.frame.widget.StarView;
import com.paishen.peiniwan.module.message.EaseChatActivity;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import de.greenrobot.event.EventBus;

public class ProfileInfoActivity extends BaseActivity {
    public static final String EXTRA_MODE_CHAT = "extra_mode_chat";
    public static final String EXTRA_SHOWN_USER_ID = "extra_shown_u_id";
    private long shownUserId;
    private com.paishen.peiniwan.database.User dbUser;
    private List<com.paishen.peiniwan.database.Photo> dbPhotoList;

    private ColorEvaluator colorEvaluator = new ColorEvaluator();
    private int dipTitle100;

    private TextView txToDate;

    private TitleLayout layTitle;
    private ImageView viewBack;
    private ImageView imgConcern;
    private boolean isConcern;

    private PictureLayout layPicture;

    private RecyclerView viewRecycler;
    private LinearLayoutManager layoutManager;
    private ProfileInfoAdapter adapter;

    private long lastCommentId = -1;
    private boolean fetchOver = false;

    private boolean isTitleShown = false;
    private boolean isTitleAnimChanging = false;

    private ValueAnimator animShowTitle, animHideTitle;

    private ViewGroup layOnce;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        shownUserId = getIntent().getLongExtra(EXTRA_SHOWN_USER_ID, -1);

        isSupportTouchBack = false;
        setContentView(R.layout.activity_profile_info);

        layPicture = (PictureLayout) findViewById(R.id.lay_picture);

        layTitle = (TitleLayout) findViewById(R.id.lay_title);
        layTitle.setLineVisibility(View.GONE);
        imgConcern = (ImageView) LayoutInflater.from(this).inflate(R.layout.layout_title_menu_image, null);
        imgConcern.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestSquareCollect();
            }
        });
        layTitle.pushContent(viewBack = makeBackView(false), getString(R.string.profile_detail_info), imgConcern, false);
        layTitle.setBackgroundColor(0x00000000);
        layTitle.setCurrContentCenterAlpha(0);
        dipTitle100 = BaseUtil.dip2px(100);
        imgConcern.setVisibility(View.INVISIBLE);

        viewRecycler = (RecyclerView) findViewById(R.id.view_recycler);
        viewRecycler.setLayoutManager(layoutManager = new LinearLayoutManager(this));
        viewRecycler.setAdapter(adapter = new ProfileInfoAdapter());
        viewRecycler.setItemAnimator(null);
        adapter.attachPictureLayout(layPicture);
        viewRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private int currY;
            private boolean scrollDown = false;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scrollDown = dy > 0;

                currY += dy;

                if (currY <= dipTitle100 * 1.55f) {
                    if (isTitleShown) animHideTitle();

                } else {
                    if (!isTitleShown) animShowTitle();
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        int lastVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition();
                        int totalItemCount = layoutManager.getItemCount();
                        if (lastVisibleItem >= (totalItemCount - 1) && scrollDown) {
                            if (!fetchOver) {
                                requestCommentGet(lastCommentId);
                            }
                        }

                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        break;
                }
            }
        });

        UserDao userDao = App.i().getCurrDaoSession().getUserDao();
        dbUser = userDao.queryBuilder().where(UserDao.Properties.Id.eq(shownUserId)).unique();

        PhotoDao photoDao = App.i().getCurrDaoSession().getPhotoDao();
        dbPhotoList = photoDao.queryBuilder().where(PhotoDao.Properties.UserId.eq(shownUserId)).orderDesc(PhotoDao.Properties.Id).limit(20).list();

        adapter.setHead(dbUser);
        adapter.setPhoto(dbPhotoList);
        adapter.setBase(dbUser);
        adapter.setTag(dbUser);
        adapter.setGift(dbUser);

        txToDate = (TextView) findViewById(R.id.tx_to_date);
        if (shownUserId != App.i().getUser().getId() && getIntent().getBooleanExtra(EXTRA_MODE_CHAT, true)
                && dbUser != null && !TextUtils.isEmpty(dbUser.getEasemob_username())) {
            txToDate.setVisibility(View.VISIBLE);
            layOnce = (ViewGroup) findViewById(R.id.lay_once);
            Once.getInstance().coverProfileInfo(this, layOnce);
            txToDate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(v.getContext(), EaseChatActivity.class);
                    intent.putExtra(EaseConstant.EXTRA_USER_ID, dbUser.getEasemob_username());
                    intent.putExtra(EaseChatFragment.EXTRA_OTHER_NICK, dbUser.getNickname());
                    intent.putExtra(EaseChatFragment.EXTRA_SELF_NICK, App.i().getUser().getNickname());
                    startActivity(intent);
                }
            });
        }

        requestUserInfo();

        if (shownUserId != App.i().getUser().getId()) {
            requestUserCheckCollected();
        }
    }

    private void animShowTitle() {
        if (!isTitleAnimChanging) {
            animShowTitle = ValueAnimator.ofFloat(0f, 1f);
            animShowTitle.setDuration(500);
            animShowTitle.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float fraction = (float) animation.getAnimatedValue();
                    layTitle.setBackgroundColor(colorEvaluator.evaluate(fraction, 0x00000000, 0xFFFFFFFF));
                    layTitle.setCurrContentCenterAlpha(fraction);
                }
            });
            animShowTitle.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    layTitle.setBackgroundColor(0xFFFFFFFF);
                    layTitle.setCurrContentCenterAlpha(1);
                    isTitleAnimChanging = false;

                }

                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                    viewBack.setImageResource(R.mipmap.common_back);
                    isTitleShown = true;
                    layTitle.setLineVisibility(View.VISIBLE);
                    notifyMenuPraiseImageResource();

                }
            });
            isTitleAnimChanging = true;
            animShowTitle.start();
        }
    }

    private void animHideTitle() {
        if (!isTitleAnimChanging) {
            animHideTitle = ValueAnimator.ofFloat(1f, 0f);
            animHideTitle.setDuration(500);
            animHideTitle.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float fraction = (float) animation.getAnimatedValue();
                    layTitle.setBackgroundColor(colorEvaluator.evaluate(fraction, 0x00000000, 0xFFFFFFFF));
                    layTitle.setCurrContentCenterAlpha(fraction);
                }
            });
            animHideTitle.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    layTitle.setBackgroundColor(0x00000000);
                    layTitle.setCurrContentCenterAlpha(0);
                    isTitleAnimChanging = false;

                }

                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                    viewBack.setImageResource(R.mipmap.common_back_white);
                    isTitleShown = false;
                    layTitle.setLineVisibility(View.GONE);
                    notifyMenuPraiseImageResource();
                }
            });
            isTitleAnimChanging = true;
            animHideTitle.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (animShowTitle != null) animShowTitle.cancel();
        if (animHideTitle != null) animHideTitle.cancel();

        EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, dbUser));
    }

    private void requestSquareCollect() {
        PnwHttpManager.Square.collect(TAG, shownUserId, new PnwOkCallbackAdapter<HttpRespData<CollectedInfo>>() {
            @Override
            public void onResponse(HttpRespData<CollectedInfo> response, boolean fresh) {
                super.onResponse(response, fresh);
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    isConcern = TextUtils.equals(response.data.status, CollectedInfo.STATUS_SUCCEED);
                    int cc = dbUser.getConcern();
                    cc = cc + (isConcern ? 1 : -1);
                    dbUser.setConcern(cc);
                    adapter.setHead(dbUser);
                    notifyMenuPraiseImageResource();
                }
            }
        });
    }

    private void notifyMenuPraiseImageResource() {
        int normalRes = isTitleShown ? R.mipmap.common_heart_40_red_normal : R.mipmap.common_heart_40_white_normal;
        imgConcern.setImageResource(isConcern ? R.mipmap.common_heart_40_light : normalRes);
    }

    private void requestUserCheckCollected() {
        PnwHttpManager.User.checkCollected(TAG, shownUserId, new PnwOkCallbackAdapter<HttpRespData<CollectedInfo>>() {
            @Override
            public void onResponse(HttpRespData<CollectedInfo> response, boolean fresh) {
                super.onResponse(response, fresh);
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    isConcern = response.data.is_collected;
                    notifyMenuPraiseImageResource();
                    imgConcern.setEnabled(true);
                    imgConcern.setVisibility(View.VISIBLE);
                    ObjectAnimator animator = ObjectAnimator.ofFloat(imgConcern, "alpha", 0f, 1f);
                    animator.setDuration(1000);
                    animator.start();
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                // do nothing
            }
        });
    }

    private void requestUserInfo() {
        PnwHttpManager.User.info(TAG, shownUserId, new PnwOkCallbackAdapter<HttpRespData<User>>() {
            @Override
            public void onResponse(HttpRespData<User> response, boolean fresh) {
                super.onResponse(response, fresh);

                if (response.errcode == C.http.RESULT_SUCCESS) {
                    dbUser = ModelConverter.mergeOrReplace(dbUser, response.data);
                    adapter.setHead(dbUser);

                    requestUserGetPhoto();

                    if (shownUserId != App.i().getUser().getId() && getIntent().getBooleanExtra(EXTRA_MODE_CHAT, true)
                            && dbUser != null && !TextUtils.isEmpty(dbUser.getEasemob_username())) {
                        if (layOnce == null) {
                            layOnce = (ViewGroup) findViewById(R.id.lay_once);
                            Once.getInstance().coverProfileInfo(ProfileInfoActivity.this, layOnce);
                        }

                        txToDate.setVisibility(View.VISIBLE);
                        txToDate.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(v.getContext(), EaseChatActivity.class);
                                intent.putExtra(EaseConstant.EXTRA_USER_ID, dbUser.getEasemob_username());
                                intent.putExtra(EaseChatFragment.EXTRA_OTHER_NICK, dbUser.getNickname());
                                intent.putExtra(EaseChatFragment.EXTRA_SELF_NICK, App.i().getUser().getNickname());
                                startActivity(intent);
                            }
                        });
                    }
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                adapter.setHead(dbUser);
                adapter.setPhoto(dbPhotoList);
                adapter.setBase(dbUser);
                adapter.setTag(dbUser);
                adapter.setGift(dbUser);
            }
        });
    }

    private void requestUserGetPhoto() {
        PnwHttpManager.User.getPhoto(TAG, shownUserId, new PnwOkCallbackAdapter<HttpRespData<List<Photo>>>() {
            @Override
            public void onResponse(HttpRespData<List<Photo>> response, boolean fresh) {
                super.onResponse(response, fresh);
                if (response.errcode == C.http.RESULT_SUCCESS) {

                    PhotoDao photoDao = App.i().getCurrDaoSession().getPhotoDao();
                    List<com.paishen.peiniwan.database.Photo> photoList = new ArrayList<>();
                    for (Photo p : response.data) {
                        photoList.add(ModelConverter.mergeOrReplace(null, p, shownUserId));
                    }
                    photoDao.insertOrReplaceInTx(photoList);
                    adapter.setPhoto(photoList);

                    adapter.setBase(dbUser);
                    adapter.setTag(dbUser);
                    adapter.setGift(dbUser);
                    requestCommentGet(lastCommentId);
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                adapter.setPhoto(dbPhotoList);
                adapter.setBase(dbUser);
                adapter.setTag(dbUser);
                adapter.setGift(dbUser);
            }
        });
    }


    private void requestCommentGet(long lid) {
        PnwHttpManager.Comment.get(TAG, shownUserId, lid, new PnwOkCallbackAdapter<HttpRespData<CommentInfo>>() {
            @Override
            public void onResponse(HttpRespData<CommentInfo> response, boolean fresh) {
                super.onResponse(response, fresh);
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    if (response.data != null && response.data.comments != null) {
                        int commentFetchCount = 5;
                        boolean b = lastCommentId > 0 ? adapter.appendComment(response.data.comments, fetchOver = response.data.comments.size() < commentFetchCount)
                                : adapter.setComment(response.data.count, response.data.comments, fetchOver = response.data.comments.size() < commentFetchCount);

                        if (response.data.comments.size() > 0) {
                            lastCommentId = response.data.comments.get(response.data.comments.size() - 1).id;
                        }
                    }
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
            }
        });
    }


    static final class ProfileInfoAdapter extends RecyclerView.Adapter<ProfileInfoAdapter.ViewHolder> {
        static class InfoElement {
            public static final int TYPE_HEAD = 1;
            public static final int TYPE_PHOTO = 2;
            public static final int TYPE_BASE = 3;
            public static final int TYPE_TAG = 4;
            public static final int TYPE_GIFT = 5;
            public static final int TYPE_COMMENT = 6;
            public static final int TYPE_COMMENT_TITLE = 7;
            public static final int TYPE_LOAD = 8;
            public int type;
            public Object element;
        }

        private final List<InfoElement> infoElements = new ArrayList<>();
        private final int dip5, dip4, dip9;

        private PictureLayout layPicture;
        private List<com.paishen.peiniwan.database.Photo> mPhotoList;

        ProfileInfoAdapter() {
            final float scale = App.i().getResources().getDisplayMetrics().density;
            dip5 = (int) (5 * scale + 0.5f);
            dip4 = (int) (4 * scale + 0.5f);
            dip9 = (int) (9 * scale + 0.5f);
        }

        public void attachPictureLayout(PictureLayout view) {
            layPicture = view;
        }

        public void set(List<InfoElement> dataList) {
            infoElements.clear();
            infoElements.addAll(dataList);
            notifyDataSetChanged();
        }

        public void setHead(com.paishen.peiniwan.database.User user) {
            LogUtil.t("ProfileInfoActivity setHead");
            ProfileInfoAdapter.InfoElement head = new ProfileInfoAdapter.InfoElement();
            head.type = ProfileInfoAdapter.InfoElement.TYPE_HEAD;
            head.element = user;
            if (infoElements.size() > 0) {
                infoElements.set(0, head);
                notifyItemChanged(0);
            } else {
                infoElements.add(head);
                notifyItemInserted(0);
            }
        }

        public void setPhoto(List<com.paishen.peiniwan.database.Photo> photoList) {
            LogUtil.t("ProfileInfoActivity setPhoto");
            if (photoList != null) {
                mPhotoList = photoList;
                int originalSize = 0;
                Iterator<InfoElement> ieIterator = infoElements.iterator();
                while (ieIterator.hasNext()) {
                    InfoElement curr = ieIterator.next();
                    if (curr.type == InfoElement.TYPE_PHOTO) {
                        ieIterator.remove();
                        originalSize++;
                    }
                }
                notifyItemRangeRemoved(1, originalSize);

                int lineIdx = 0;
                for (int i = 0; i < photoList.size(); i = i + 4) {
                    List<com.paishen.peiniwan.database.Photo> rows = new ArrayList<>();
                    if (i < photoList.size()) rows.add(photoList.get(i));
                    if (i + 1 < photoList.size()) rows.add(photoList.get(i + 1));
                    if (i + 2 < photoList.size()) rows.add(photoList.get(i + 2));
                    if (i + 3 < photoList.size()) rows.add(photoList.get(i + 3));

                    ProfileInfoAdapter.InfoElement photo = new ProfileInfoAdapter.InfoElement();
                    photo.type = InfoElement.TYPE_PHOTO;
                    photo.element = rows;
                    lineIdx = lineIdx + 1;
                    infoElements.add(lineIdx, photo);
                }
                notifyItemRangeInserted(1, lineIdx);

            }
        }

        public void setBase(com.paishen.peiniwan.database.User user) {
            LogUtil.t("ProfileInfoActivity setBase");
            if (user != null) {
                ProfileInfoAdapter.InfoElement base = new ProfileInfoAdapter.InfoElement();
                base.type = InfoElement.TYPE_BASE;
                base.element = user;
                for (int i = infoElements.size() - 1; i >= 0; i--) {
                    if (infoElements.get(i).type == InfoElement.TYPE_BASE) {
                        infoElements.set(i, base);
                        notifyItemChanged(i);
                        return;
                    } else if (infoElements.get(i).type == InfoElement.TYPE_PHOTO) {
                        infoElements.add(i + 1, base);
                        notifyItemInserted(i + 1);
                        return;
                    } else if (infoElements.get(i).type == InfoElement.TYPE_HEAD) {
                        infoElements.add(i + 1, base);
                        notifyItemInserted(i + 1);
                        return;
                    }
                }
                LogUtil.e("photo elements order error");
            }
        }

        public void setTag(com.paishen.peiniwan.database.User user) {
            LogUtil.t("ProfileInfoActivity setTag");
            if (user != null) {
                if (TextUtils.isEmpty(user.getTags())) {
                    return;
                }
                List<UserTag> userTagList = App.i().getGson().fromJson(new String(Base64.decode(user.getTags(), Base64.DEFAULT)), new TypeToken<List<UserTag>>() {
                }.getType());
                String[] arrHobby = userTagList.get(0).tag_name;
                String[] arrSpecialty = userTagList.get(1).tag_name;
                String[] arrAbility = userTagList.get(2).tag_name;
                if (arrHobby.length == 0 && arrSpecialty.length == 0 && arrAbility.length == 0) {
                    return;
                }

                ProfileInfoAdapter.InfoElement base = new ProfileInfoAdapter.InfoElement();
                base.type = InfoElement.TYPE_TAG;
                base.element = user;
                for (int i = infoElements.size() - 1; i >= 0; i--) {
                    if (infoElements.get(i).type == InfoElement.TYPE_TAG) {
                        infoElements.set(i, base);
                        notifyItemChanged(i);
                        return;
                    } else if (infoElements.get(i).type == InfoElement.TYPE_BASE) {
                        infoElements.add(i + 1, base);
                        notifyItemInserted(i + 1);
                        return;
                    }
                }
                LogUtil.e("photo elements order error [TYPE_BASE not found]");
            }
        }

        public void setGift(com.paishen.peiniwan.database.User user) {
            LogUtil.t("ProfileInfoActivity setGift");
            if (user != null) {
                ProfileInfoAdapter.InfoElement base = new ProfileInfoAdapter.InfoElement();
                base.type = InfoElement.TYPE_GIFT;
                base.element = user;
                for (int i = infoElements.size() - 1; i >= 0; i--) {
                    if (infoElements.get(i).type == InfoElement.TYPE_GIFT) {
                        infoElements.set(i, base);
                        notifyItemChanged(i);
                        return;
                    } else if (infoElements.get(i).type == InfoElement.TYPE_TAG) {
                        infoElements.add(i + 1, base);
                        notifyItemInserted(i + 1);
                        return;
                    }
                }
                LogUtil.e("photo elements order error [TYPE_TAG not found]");
            }
        }

        public boolean setComment(int totalCount, List<CommentInfo.Comment> comments, boolean fetchOver) {
            LogUtil.t("ProfileInfoActivity setComment");
            if (comments != null) {
                int originalSize = 0;
                Iterator<InfoElement> ieIterator = infoElements.iterator();
                while (ieIterator.hasNext()) {
                    InfoElement curr = ieIterator.next();
                    if (curr.type == InfoElement.TYPE_COMMENT
                            || curr.type == InfoElement.TYPE_COMMENT_TITLE
                            || curr.type == InfoElement.TYPE_LOAD) {
                        ieIterator.remove();
                        originalSize++;
                    }
                }
                notifyItemRangeRemoved(infoElements.size() - 1 - originalSize, originalSize);

                int lineIdx = 0;
                ProfileInfoAdapter.InfoElement commentTitle = new ProfileInfoAdapter.InfoElement();
                commentTitle.type = InfoElement.TYPE_COMMENT_TITLE;
                commentTitle.element = totalCount;
                infoElements.add(commentTitle);
                lineIdx = lineIdx + 1;

                for (CommentInfo.Comment c : comments) {
                    ProfileInfoAdapter.InfoElement comment = new ProfileInfoAdapter.InfoElement();
                    comment.type = InfoElement.TYPE_COMMENT;
                    comment.element = c;
                    infoElements.add(comment);
                    lineIdx++;
                }

                if (!fetchOver) {
                    ProfileInfoAdapter.InfoElement comment = new ProfileInfoAdapter.InfoElement();
                    comment.type = InfoElement.TYPE_LOAD;
                    comment.element = "";
                    infoElements.add(comment);
                    lineIdx++;
                }
                notifyItemRangeInserted(infoElements.size() - lineIdx, lineIdx);


                return true;
            }
            return false;
        }

        public boolean appendComment(List<CommentInfo.Comment> comments, boolean fetchOver) {
            LogUtil.t("ProfileInfoActivity appendComment");
            if (comments != null) {
                InfoElement ieLoad = infoElements.get(infoElements.size() - 1);
                infoElements.remove(ieLoad);
                notifyItemRemoved(infoElements.size() - 1);

                int lineIdx = 0;
                for (CommentInfo.Comment c : comments) {
                    ProfileInfoAdapter.InfoElement comment = new ProfileInfoAdapter.InfoElement();
                    comment.type = InfoElement.TYPE_COMMENT;
                    comment.element = c;
                    infoElements.add(comment);
                    lineIdx++;
                }
                if (!fetchOver) {
                    ProfileInfoAdapter.InfoElement comment = new ProfileInfoAdapter.InfoElement();
                    comment.type = InfoElement.TYPE_LOAD;
                    comment.element = "";
                    infoElements.add(comment);
                    lineIdx++;
                }
                notifyItemRangeInserted(infoElements.size() - lineIdx, lineIdx);
                return true;
            }

            return false;
        }


        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(View view) {
                super(view);
            }
        }

        public class ViewHolderTop extends ViewHolder {
            private View layTop, layAvatar, layCF;
            private TextView txNickname;
            private ImageView imgGender;
            private ImageView imgAvatar;
            private TextView txIntro;
            private TextView txFans, txConcern;

            public ViewHolderTop(View view) {
                super(view);
            }
        }

        public class ViewHolderPhoto extends ViewHolder {
            private ImageView imgPhoto1, imgPhoto2, imgPhoto3, imgPhoto4;

            public ViewHolderPhoto(View view) {
                super(view);
            }
        }

        public class ViewHolderBase extends ViewHolder {
            TextView txHeight, txWeight, txAge, txConstellation, txDegree, txProfession, txSalary, txAddress;

            public ViewHolderBase(View view) {
                super(view);
            }
        }

        public class ViewHolderTag extends ViewHolder {
            private View layAbilityWrapper, layHobbyWrapper, laySpecialtyWrapper;
            private ViewGroup layAbility, layHobby, laySpecialty;

            public ViewHolderTag(View view) {
                super(view);
            }
        }

        public class ViewHolderGift extends ViewHolder {
            private TextView txGift1, txGift5, txGift10;

            public ViewHolderGift(View view) {
                super(view);
            }
        }

        public class ViewHolderCommentTitle extends ViewHolder {
            private TextView txCount;

            public ViewHolderCommentTitle(View view) {
                super(view);
            }
        }

        public class ViewHolderComment extends ViewHolder {
            private ImageView imgAvatar;
            private StarView viewStar;
            private TextView txNickname, txContent, txTime;

            public ViewHolderComment(View view) {
                super(view);
            }
        }

        public class ViewHolderLoad extends ViewHolder {
            public ViewHolderLoad(View view) {
                super(view);
            }
        }

        @Override
        public int getItemCount() {
            return infoElements.size();
        }


        @Override
        public int getItemViewType(int position) {
            return infoElements.get(position).type;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
            switch (type) {
                case InfoElement.TYPE_HEAD:
                    View viewTop = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_profile_info_top, viewGroup, false);
                    ViewHolderTop vhTop = new ViewHolderTop(viewTop);

                    vhTop.layTop = viewTop.findViewById(R.id.lay_top);
                    final float scale = viewGroup.getContext().getResources().getDisplayMetrics().density;
                    int topHeight4_4 = (int) (226 * scale + 0.5f);
                    LinearLayout.LayoutParams lpHead = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, topHeight4_4 + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0));
                    vhTop.layTop.setLayoutParams(lpHead);
                    vhTop.layCF = viewTop.findViewById(R.id.lay_c_f);
                    vhTop.layAvatar = viewTop.findViewById(R.id.lay_avatar);
                    vhTop.layAvatar.setOnClickListener(onAvatarClickListener);
                    vhTop.imgAvatar = (ImageView) viewTop.findViewById(R.id.img_avatar);
                    vhTop.txIntro = (TextView) viewTop.findViewById(R.id.tx_intro);
                    vhTop.txNickname = (TextView) viewTop.findViewById(R.id.tx_nickname);
                    vhTop.imgGender = (ImageView) viewTop.findViewById(R.id.img_gender);
                    vhTop.txFans = (TextView) viewTop.findViewById(R.id.tx_fans);
                    vhTop.txConcern = (TextView) viewTop.findViewById(R.id.tx_concern);
                    return vhTop;
                case InfoElement.TYPE_PHOTO:
                    View viewPhoto = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_profile_info_photo, viewGroup, false);
                    ViewHolderPhoto vhPhoto = new ViewHolderPhoto(viewPhoto);
                    vhPhoto.imgPhoto1 = (ImageView) viewPhoto.findViewById(R.id.img_photo_1);
                    vhPhoto.imgPhoto1.setOnClickListener(onPhotoClickListener);
                    vhPhoto.imgPhoto2 = (ImageView) viewPhoto.findViewById(R.id.img_photo_2);
                    vhPhoto.imgPhoto2.setOnClickListener(onPhotoClickListener);
                    vhPhoto.imgPhoto3 = (ImageView) viewPhoto.findViewById(R.id.img_photo_3);
                    vhPhoto.imgPhoto3.setOnClickListener(onPhotoClickListener);
                    vhPhoto.imgPhoto4 = (ImageView) viewPhoto.findViewById(R.id.img_photo_4);
                    vhPhoto.imgPhoto4.setOnClickListener(onPhotoClickListener);
                    return vhPhoto;
                case InfoElement.TYPE_BASE:
                    View viewBase = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_profile_info_base, viewGroup, false);
                    ViewHolderBase vhBase = new ViewHolderBase(viewBase);
                    vhBase.txHeight = (TextView) viewBase.findViewById(R.id.tx_height);
                    vhBase.txWeight = (TextView) viewBase.findViewById(R.id.tx_weight);
                    vhBase.txAge = (TextView) viewBase.findViewById(R.id.tx_age);
                    vhBase.txConstellation = (TextView) viewBase.findViewById(R.id.tx_constellation);
                    vhBase.txDegree = (TextView) viewBase.findViewById(R.id.tx_degree);
                    vhBase.txProfession = (TextView) viewBase.findViewById(R.id.tx_profession);
                    vhBase.txSalary = (TextView) viewBase.findViewById(R.id.tx_salary);
                    vhBase.txAddress = (TextView) viewBase.findViewById(R.id.tx_address);
                    return vhBase;
                case InfoElement.TYPE_TAG:
                    View viewTag = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_profile_info_tag, viewGroup, false);
                    ViewHolderTag vhTag = new ViewHolderTag(viewTag);
                    vhTag.layAbility = (ViewGroup) viewTag.findViewById(R.id.lay_ability);
                    vhTag.layAbilityWrapper = viewTag.findViewById(R.id.lay_ability_wrapper);
                    vhTag.layHobby = (ViewGroup) viewTag.findViewById(R.id.lay_hobby);
                    vhTag.layHobbyWrapper = viewTag.findViewById(R.id.lay_hobby_wrapper);
                    vhTag.laySpecialty = (ViewGroup) viewTag.findViewById(R.id.lay_specialty);
                    vhTag.laySpecialtyWrapper = viewTag.findViewById(R.id.lay_specialty_wrapper);
                    return vhTag;
                case InfoElement.TYPE_GIFT:
                    View viewGift = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_profile_info_gift, viewGroup, false);
                    ViewHolderGift vhGift = new ViewHolderGift(viewGift);
                    vhGift.txGift1 = (TextView) viewGift.findViewById(R.id.tx_gift_1);
                    vhGift.txGift5 = (TextView) viewGift.findViewById(R.id.tx_gift_5);
                    vhGift.txGift10 = (TextView) viewGift.findViewById(R.id.tx_gift_10);
                    return vhGift;
                case InfoElement.TYPE_COMMENT:
                    View viewComment = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_profile_info_comment, viewGroup, false);
                    ViewHolderComment vhComment = new ViewHolderComment(viewComment);
                    vhComment.imgAvatar = (ImageView) viewComment.findViewById(R.id.img_avatar);
                    vhComment.viewStar = (StarView) viewComment.findViewById(R.id.view_star);
                    vhComment.txNickname = (TextView) viewComment.findViewById(R.id.tx_nickname);
                    vhComment.txContent = (TextView) viewComment.findViewById(R.id.tx_content);
                    vhComment.txTime = (TextView) viewComment.findViewById(R.id.tx_time);
                    return vhComment;
                case InfoElement.TYPE_COMMENT_TITLE:
                    View viewCommentTitle = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_profile_info_comment_title, viewGroup, false);
                    ViewHolderCommentTitle vhCommentTitle = new ViewHolderCommentTitle(viewCommentTitle);
                    vhCommentTitle.txCount = (TextView) viewCommentTitle.findViewById(R.id.tx_count);
                    return vhCommentTitle;
                case InfoElement.TYPE_LOAD:
                    View viewLoad = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.frame_recycler_load, viewGroup, false);
                    return new ViewHolderLoad(viewLoad);
                default:
                    throw new IllegalArgumentException("ProfileInfoAdapter error type :" + type);
            }
        }

        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
            final InfoElement se = infoElements.get(position);
            switch (se.type) {
                case InfoElement.TYPE_HEAD:
                    final ViewHolderTop vhTop = (ViewHolderTop) viewHolder;
                    final com.paishen.peiniwan.database.User userTop = (com.paishen.peiniwan.database.User) se.element;
                    if (userTop != null) {
                        String shownAvatarUrl = "";
                        if (!TextUtils.isEmpty(userTop.getHead_img_url_max())) {
                            shownAvatarUrl = userTop.getHead_img_url_max();
                        } else {
                            shownAvatarUrl = userTop.getHead_img_url();
                        }

                        vhTop.layAvatar.setTag(shownAvatarUrl);
                        Glide.with(vhTop.itemView.getContext()).load(userTop.getHead_img_url())
                                .placeholder(R.mipmap.common_avatar_c_170)
                                .bitmapTransform(App.i().getCropCircleTransformation()).into(vhTop.imgAvatar);

                        vhTop.txIntro.setText(TextUtils.isEmpty(userTop.getIntro()) ? App.i().getString(R.string.profile_intro_tips) : userTop.getIntro());
                        vhTop.txNickname.setText(userTop.getNickname());

                        vhTop.layCF.setVisibility(View.VISIBLE);
                        vhTop.txFans.setText(String.valueOf(userTop.getFans()));
                        vhTop.txConcern.setText(String.valueOf(userTop.getConcern()));


                        vhTop.imgGender.setImageResource(userTop.getGender()
                                ? R.mipmap.square_list_gender_male : R.mipmap.square_list_gender_female);

                    }
                    break;
                case InfoElement.TYPE_PHOTO:
                    ViewHolderPhoto vhPhoto = (ViewHolderPhoto) viewHolder;
                    List<com.paishen.peiniwan.database.Photo> rows = (List<com.paishen.peiniwan.database.Photo>) se.element;
                    vhPhoto.imgPhoto1.setVisibility(View.INVISIBLE);
                    vhPhoto.imgPhoto2.setVisibility(View.INVISIBLE);
                    vhPhoto.imgPhoto3.setVisibility(View.INVISIBLE);
                    vhPhoto.imgPhoto4.setVisibility(View.INVISIBLE);
                    switch (rows.size()) {
                        default:
                        case 4:
                            vhPhoto.imgPhoto4.setTag(R.id.frame_picture_url, rows.get(3).getPhoto_url());
                            vhPhoto.imgPhoto4.setVisibility(View.VISIBLE);
                            Glide.with(vhPhoto.itemView.getContext()).load(rows.get(3).getPhoto_url()).placeholder(R.mipmap.common_pic_s_180).into(vhPhoto.imgPhoto4);
                        case 3:
                            vhPhoto.imgPhoto3.setTag(R.id.frame_picture_url, rows.get(2).getPhoto_url());
                            vhPhoto.imgPhoto3.setVisibility(View.VISIBLE);
                            Glide.with(vhPhoto.itemView.getContext()).load(rows.get(2).getPhoto_url()).placeholder(R.mipmap.common_pic_s_180).into(vhPhoto.imgPhoto3);
                        case 2:
                            vhPhoto.imgPhoto2.setTag(R.id.frame_picture_url, rows.get(1).getPhoto_url());
                            vhPhoto.imgPhoto2.setVisibility(View.VISIBLE);
                            Glide.with(vhPhoto.itemView.getContext()).load(rows.get(1).getPhoto_url()).placeholder(R.mipmap.common_pic_s_180).into(vhPhoto.imgPhoto2);
                        case 1:
                            vhPhoto.imgPhoto1.setTag(R.id.frame_picture_url, rows.get(0).getPhoto_url());
                            vhPhoto.imgPhoto1.setVisibility(View.VISIBLE);
                            Glide.with(vhPhoto.itemView.getContext()).load(rows.get(0).getPhoto_url()).placeholder(R.mipmap.common_pic_s_180).into(vhPhoto.imgPhoto1);
                        case 0:
                            break;
                    }
                    break;
                case InfoElement.TYPE_BASE:
                    ViewHolderBase vhBase = (ViewHolderBase) viewHolder;
                    com.paishen.peiniwan.database.User userBase = (com.paishen.peiniwan.database.User) se.element;
                    if (!TextUtils.isEmpty(userBase.getHeight()))
                        vhBase.txHeight.setText(userBase.getHeight());
                    if (!TextUtils.isEmpty(userBase.getWeight()))
                        vhBase.txWeight.setText(userBase.getWeight());
                    if (!TextUtils.isEmpty(userBase.getAge()))
                        vhBase.txAge.setText(userBase.getAge());
                    if (!TextUtils.isEmpty(userBase.getConstellation()))
                        vhBase.txConstellation.setText(userBase.getConstellation());
                    if (!TextUtils.isEmpty(userBase.getDegree()))
                        vhBase.txDegree.setText(userBase.getDegree());
                    if (!TextUtils.isEmpty(userBase.getProfession()))
                        vhBase.txProfession.setText(userBase.getProfession());
                    if (!TextUtils.isEmpty(userBase.getSalary()))
                        vhBase.txSalary.setText(userBase.getSalary());
                    if (!TextUtils.isEmpty(userBase.getCity()))
                        vhBase.txAddress.setText(userBase.getCity());
                    break;
                case InfoElement.TYPE_TAG:
                    ViewHolderTag vhTag = (ViewHolderTag) viewHolder;
                    com.paishen.peiniwan.database.User userTag = (com.paishen.peiniwan.database.User) se.element;

                    List<UserTag> userTagList = App.i().getGson().fromJson(new String(Base64.decode(userTag.getTags(), Base64.DEFAULT)), new TypeToken<List<UserTag>>() {
                    }.getType());
                    String[] arrHobby = userTagList.get(0).tag_name;
                    String[] arrSpecialty = userTagList.get(1).tag_name;
                    String[] arrAbility = userTagList.get(2).tag_name;

                    if (arrHobby != null) {
                        vhTag.layHobbyWrapper.setVisibility(arrHobby.length > 0 ? View.VISIBLE : View.GONE);
                        vhTag.layHobby.removeAllViewsInLayout();
                        for (String hobby : arrHobby) {
                            vhTag.layHobby.addView(makeTagView(vhTag.itemView.getContext(), hobby, R.drawable.profile_info_shape_tag_hobby));
                        }
                    } else {
                        vhTag.layHobbyWrapper.setVisibility(View.GONE);
                    }

                    if (arrSpecialty != null) {
                        vhTag.laySpecialtyWrapper.setVisibility(arrSpecialty.length > 0 ? View.VISIBLE : View.GONE);
                        vhTag.laySpecialty.removeAllViewsInLayout();
                        for (String hobby : arrSpecialty) {
                            vhTag.laySpecialty.addView(makeTagView(vhTag.itemView.getContext(), hobby, R.drawable.profile_info_shape_tag_specialty));
                        }
                    } else {
                        vhTag.laySpecialtyWrapper.setVisibility(View.GONE);
                    }
                    if (arrAbility != null) {
                        vhTag.layAbilityWrapper.setVisibility(arrAbility.length > 0 ? View.VISIBLE : View.GONE);
                        vhTag.layAbility.removeAllViewsInLayout();
                        for (String hobby : arrAbility) {
                            vhTag.layAbility.addView(makeTagView(vhTag.itemView.getContext(), hobby, R.drawable.profile_info_shape_tag_ability));
                        }
                    } else {
                        vhTag.layAbilityWrapper.setVisibility(View.GONE);
                    }
                    break;
                case InfoElement.TYPE_GIFT:
                    ViewHolderGift vhGift = (ViewHolderGift) viewHolder;
                    com.paishen.peiniwan.database.User userGift = (com.paishen.peiniwan.database.User) se.element;
                    vhGift.txGift1.setVisibility(userGift.getGift1() > 0 ? View.VISIBLE : View.GONE);
                    vhGift.txGift1.setText("x " + userGift.getGift1());
                    vhGift.txGift5.setVisibility(userGift.getGift5() > 0 ? View.VISIBLE : View.GONE);
                    vhGift.txGift5.setText("x " + userGift.getGift5());
                    vhGift.txGift10.setVisibility(userGift.getGift10() > 0 ? View.VISIBLE : View.GONE);
                    vhGift.txGift10.setText("x " + userGift.getGift10());
                    break;
                case InfoElement.TYPE_COMMENT_TITLE:
                    ViewHolderCommentTitle vhCommentTitle = (ViewHolderCommentTitle) viewHolder;
                    int count = (int) se.element;
                    vhCommentTitle.itemView.setVisibility(count > 0 ? View.VISIBLE : View.GONE);
                    vhCommentTitle.txCount.setText(App.i().getString(R.string.profile_info_comment_count, count));
                    break;
                case InfoElement.TYPE_COMMENT:
                    ViewHolderComment vhComment = (ViewHolderComment) viewHolder;
                    CommentInfo.Comment comment = (CommentInfo.Comment) se.element;

                    Glide.with(vhComment.itemView.getContext()).load(comment.created_user.head_img_url)
                            .placeholder(R.mipmap.common_avatar_c_170).bitmapTransform(App.i().getCropCircleTransformation()).into(vhComment.imgAvatar);
                    vhComment.viewStar.setLightStarCount(comment.score / StarView.TOTAL_COUNT);
                    try {
                        Date createDate = DateUtil.parse(comment.created_date, DateUtil.yyyy_MM_dd_HH_mm_ss);
                        vhComment.txTime.setText(DateUtils.getTimestampString(createDate));
                    } catch (Exception e) {
                        vhComment.txTime.setText("");
                    }
                    vhComment.txNickname.setText(comment.created_user.nickname);
                    vhComment.txContent.setText(comment.content);
                    break;
            }
        }

        private View.OnClickListener onAvatarClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String avatarUrl = (String) v.getTag();
                if (!TextUtils.isEmpty(avatarUrl)) {
                    layPicture.showPicture(avatarUrl, v);
                }
            }
        };

        private View.OnClickListener onPhotoClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (layPicture != null && v.getTag(R.id.frame_picture_url) != null) {
                    List<String> pictures = new ArrayList<>();
                    int currIdx = 0;
                    for (int i = 0; i < mPhotoList.size(); i++) {
                        String pic = mPhotoList.get(i).getPhoto_url();
                        pictures.add(pic);
                        if (TextUtils.equals(pic, String.valueOf(v.getTag(R.id.frame_picture_url)))) {
                            currIdx = i;
                        }
                    }
                    layPicture.showPicture(pictures, currIdx, v);
                }
            }
        };

        private TextView makeTagView(Context context, String text, int backgroundRes) {
            TextView t = new TextView(context);
            t.setText(text);
            t.setBackgroundResource(backgroundRes);
            ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, 0, dip5 * 2, dip5 * 2);
            t.setLayoutParams(lp);
            t.setPadding(dip9, dip4, dip9, dip4);
            t.setTextColor(0xFFFFFFFF);
            t.setTextSize(11);
            return t;
        }
    }

    @Override
    public void onBackPressed() {
        if (View.VISIBLE == layPicture.getVisibility()) {
            layPicture.hiddenPicture();
        } else {
            super.onBackPressed();
        }
    }


}
